{
======================================================================
Project  : Firebird Control Center
Unit     : uForeground.pas
Purpose  :
Author   : Achim Kalwa <delphi@achim-kalwa.de>
Compiler : Borland Delphi 5.01
----------------------------------------------------------------------
History:
2004-02-25, Kalwa:
- "-exit" command line param sends WM_EXIT_FBCC message to main
  application, causing it to quit nicely. This will be used by
  uninstaller to shut down fbcc. 
======================================================================
}
{$I fbcc.inc}
unit uForeground;

interface

uses
  Windows;

function FindWindowByName(const aCaption : String) : THandle;
procedure SwitchToThisWindow(aWnd: THandle; fAltTab: bool); stdcall;
function SwitchToWindowByName(aName : String; SecsToWait : Integer = 3) : Boolean;

implementation

uses
  Classes,
  SysUtils,
  Forms;

procedure SwitchToThisWindow; external user32 Name 'SwitchToThisWindow';

var
  WindowList : TList;

function EnumWinProc(Wnd: HWnd; param: lParam): boolean; stdcall;
begin
  WindowList.Add(Pointer(Wnd)); // add each handle to the list
  Result := true;
end;

function FindWindowByName(const aCaption : String) : THandle;
var
  i      : Integer;
  Wnd    : THandle;
  Buffer : Array[0..255] of Char;
  sHelp  : String;
begin
  WindowList := NIL;
  Try
    WindowList := TList.Create;
    ENumWindows(@ENumWinProc, 0);
    Result := 0;
    for i := 0 to WindowList.Count-1 do begin
      Wnd := THandle(WindowList[i]);
      if GetWindowText(Wnd, Buffer, SizeOf(Buffer)-1) > 0 then begin
        sHelp := StrPas(Buffer);
        if Pos(aCaption, sHelp) > 0 then begin
          Result := Wnd;
          Break;
        end;                              { if Pos... }
      end;                                { if GetWindowText }
    end;                                  { for i }
  Finally
    FreeAndNil(WindowList);
  end;
end;                                    { FindWindowByName }

function SwitchToWindowByName(aName : String; SecsToWait : Integer = 3) : Boolean;
var
  Wnd : THandle;
  n   : Integer;
begin
  { das neue Fenster in den Vordergrund bringen }
  n := SecsToWait * 3;
  Wnd := 0;
  while (Wnd = 0) and (n > 0) do begin
    Wnd := FindWindowByName(aName);
    if Wnd = 0 then begin
      Sleep(300);
      Application.ProcessMessages;
      Dec(n);
    end;
  end;

  Result := (Wnd > 0);
  if Result then SwitchToThisWindow(Wnd, True);
end;

end.
